﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using ECMS.AppService.Interfaces;
using ECMS.AppService.Model.Requests;
using ECMS.AppService.Model.Responses;
using ECMS.Infrastructure.ClientData;
using ECMS.Infrastructure.Engines;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace ECMS.Manage.Controllers
{
    public class AccountController : ECMSControllerBase
    {
        private readonly IHttpContextAccessor _accessor;
        private readonly IUserService _userService;
        public AccountController(IUserService userService, IHttpContextAccessor accessor)
        {            
            _userService = userService;
            _accessor = accessor;
        }

        #region Views

        [AllowAnonymous]
        public IActionResult Login()
        {
            return View();
        }

        public async Task<IActionResult> LogOut()
        {
            await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            return RedirectToAction("Login");
        }

        #endregion

        #region Handle
        [AllowAnonymous]
        [HttpPost]
        public async Task<ApiResult<UserResponse>> ValidateLogin([FromBody]LoginRequest request)
        {
            // 获取当前登录的IP地址
            request.LoginIP = _accessor.HttpContext.Connection.RemoteIpAddress.ToString();

            var response = await _userService.LoginAsync(request);


            if (response.Success)
            {
                await SignInAsync(response.Data);
            }
            return response;
        }
        #endregion
    }
}